package com.hope.hotel.utils.mail;


import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.security.SecureRandom;
import java.util.Properties;

public final class JavaMailUntil {
    private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
    private static final String NUMBER = "0123456789";
    private static final String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER;
    private static final SecureRandom random = new SecureRandom();
    private JavaMailUntil() {
    }

    public static Session createSession() {

        //	账号信息
        String username = "2826079730@qq.com";//	邮箱发送账号
        String password = "zbvisdljwqlodcii";//	邮箱授权码



        Properties props = new Properties();
        props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
        props.setProperty("mail.smtp.ssl.ciphers", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256");
        props.put("mail.smtp.host", "smtp.qq.com"); // QQ邮箱的SMTP服务器地址
        props.put("mail.smtp.port", "587"); // SMTP端口号
        props.put("mail.smtp.auth", "true"); // 需要验证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // TODO Auto-generated method stub
                return new PasswordAuthentication(username, password);
            }
        });

//这里进行debug的，可以进行少输出点记录
//        session.setDebug(true);
        return session;

    }

    public static String generateCode(int length) {
        if (length < 4) {  // 至少需要4位才能确保至少有一个数字和一个字母
            throw new IllegalArgumentException("Length must be at least 4");
        }

        StringBuilder sb = new StringBuilder(length);

        // 确保至少有一个小写字母
        sb.append(CHAR_LOWER.charAt(random.nextInt(CHAR_LOWER.length())));

        // 确保至少有一个大写字母
        sb.append(CHAR_UPPER.charAt(random.nextInt(CHAR_UPPER.length())));

        // 确保至少有一个数字
        sb.append(NUMBER.charAt(random.nextInt(NUMBER.length())));

        // 填充剩余的字符
        for (int i = 3; i < length; i++) {
            sb.append(DATA_FOR_RANDOM_STRING.charAt(random.nextInt(DATA_FOR_RANDOM_STRING.length())));
        }

        // 打乱字符顺序
        char[] charArray = sb.toString().toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            int randomIndex = random.nextInt(charArray.length);
            char temp = charArray[i];
            charArray[i] = charArray[randomIndex];
            charArray[randomIndex] = temp;
        }

        return new String(charArray);
    }

    public static boolean checkEmail(String email) {
        if(email == null || email.isEmpty()) return false;
        return email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
    }

}
